package com.sk.weichat.ui.message;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sk.weichat.R;
import com.sk.weichat.adapter.TabFragmentPagerAdapter;
import com.sk.weichat.bean.User;
import com.sk.weichat.db.dao.UserDao;
import com.sk.weichat.fragment.TabAttentionFragment;
import com.sk.weichat.fragment.TabFansFragment;
import com.sk.weichat.fragment.TabFriendFragment;
import com.sk.weichat.fragment.TabGroupFragment;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.groupchat.SelectContactsActivity;
import com.sk.weichat.ui.groupchat.TabSelectContactsActivity;
import com.sk.weichat.ui.nearby.UserListGatherActivity;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.ScaleTransitionPagerTitleView;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

public class TabFriendActivity extends BaseActivity implements View.OnClickListener {
    private static final String[] CHANNELS = new String[]{"好友", "关注", "粉丝", "群聊"};
    private List<String> mDataList = Arrays.asList(CHANNELS);
    private TabFragmentPagerAdapter mExamplePagerAdapter;

    private ViewPager mViewPager;
    private ArrayList<Fragment> mFragmentList;
    private TextView mTvTitle;
    private ImageView mImgRight;
    private int mTabPosition;
    private ImageView mImgEdit;

    private static final int request_edit_fans_list_code = 6782;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_friend_tab_layout);

        mTabPosition = getIntent().getIntExtra("tabPosition", 0);
        initActionBar();

        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mFragmentList = new ArrayList<>();
        mFragmentList.add(new TabFriendFragment());
        mFragmentList.add(new TabAttentionFragment());
        mFragmentList.add(new TabFansFragment());
        mFragmentList.add(new TabGroupFragment());
        mExamplePagerAdapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList);
        mViewPager.setAdapter(mExamplePagerAdapter);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setAdapter(mExamplePagerAdapter);

        initMagicIndicator();
        mViewPager.setCurrentItem(mTabPosition);  //初始化显示第一个页面
        updateTitle(mTabPosition);
    }

    private void initActionBar() {
        getSupportActionBar().hide();

        mTvTitle = (TextView) findViewById(R.id.tv_title_center);
        mTvTitle.setText("好友");
        mImgRight = findViewById(R.id.iv_title_right);
        mImgRight.setImageResource(R.drawable.icon_add);
        mImgEdit = findViewById(R.id.img_edit);

        findViewById(R.id.iv_title_left).setOnClickListener(this);
        findViewById(R.id.iv_title_right).setOnClickListener(this);
        findViewById(R.id.img_edit).setOnClickListener(this);
    }


    private void initMagicIndicator() {
        MagicIndicator magicIndicator = findViewById(R.id.magic_indicator2);
        magicIndicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {

                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setTextSize(20);
                simplePagerTitleView.setNormalColor(ContextCompat.getColor(TabFriendActivity.this, R.color.text_color_main));
                simplePagerTitleView.setSelectedColor(ContextCompat.getColor(TabFriendActivity.this, R.color.text_color_main));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setLineHeight(UIUtil.dip2px(context, 8));
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setColors(Color.parseColor("#40c4ff"));
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, mViewPager);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {

                updateTitle(position);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    public void updateTitle(int position) {
        switch (position) {
            case 0://好友
                mTvTitle.setText("好友(" + coreManager.getSelf().getFriendsCount() + ")");
                mImgRight.setImageResource(R.drawable.icon_add);
                mImgEdit.setVisibility(View.GONE);
                break;
            case 1://关注
                mTvTitle.setText("关注(" + coreManager.getSelf().getAttCount() + ")");
                mImgRight.setImageResource(R.drawable.icon_add);
                mImgEdit.setVisibility(View.GONE);
                break;
            case 2://粉丝
                mTvTitle.setText("粉丝(" + coreManager.getSelf().getFansCount() + ")");
                mImgRight.setImageResource(R.drawable.icon_add);
                mImgEdit.setVisibility(View.VISIBLE);
                mImgEdit.setImageResource(R.drawable.icon_person_edit_black);
                break;
            case 3://群聊
                mTvTitle.setText("群聊(" + coreManager.getSelf().getRoomCount() + ")");
                mImgRight.setImageResource(R.mipmap.icon_more_black);
                mImgEdit.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                finish();
                break;

            case R.id.iv_title_right:
                if (mViewPager.getCurrentItem() == 3) {//群聊
//                    startActivity(new Intent(this, SelectContactsActivity.class));
                    startActivity(new Intent(this, TabSelectContactsActivity.class));
                } else {//加好友
                    startActivity(new Intent(this, UserListGatherActivity.class));
                }
                break;

            case R.id.img_edit:
                if (((TabFansFragment) (mFragmentList.get(2))).getmSortFriends().size() > 0) {
                    //粉丝编辑删除
                    TabFansEditActivity.startTabFansEditActivity(this, (ArrayList<User>) ((TabFansFragment) (mFragmentList.get(2))).getmSortFriends(), request_edit_fans_list_code);
                }
                break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == request_edit_fans_list_code && resultCode == Activity.RESULT_OK) {// 移除粉丝后刷新界面
            ((TabFansFragment) mFragmentList.get(2)).refreshData();
            ((TabFriendFragment) mFragmentList.get(0)).refreshData();
        }
    }

    /**
     * 下载个人基本资料
     */
    public void downloadUserInfo() {
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);

        HttpUtils.get().url(coreManager.getConfig().USER_GET_URL)
                .params(params)
                .build()
                .execute(new BaseCallback<User>(User.class) {

                    @Override
                    public void onResponse(ObjectResult<User> result) {
                        boolean updateSuccess = false;
                        if (result.getResultCode() == 1) {
                            User user = result.getData();
                            user.setIsQQBand(TextUtils.isEmpty(user.getQqUser().getNickname()) ? 0 : 1);
                            user.setQqNickName(TextUtils.isEmpty(user.getQqUser().getNickname()) ? "" : user.getQqUser().getNickname());

                            user.setIsWXBand(TextUtils.isEmpty(user.getWxUser().getNickname()) ? 0 : 1);
                            user.setWxNikeName(TextUtils.isEmpty(user.getWxUser().getNickname()) ? "" : user.getWxUser().getNickname());
                            updateSuccess = UserDao.getInstance().updateByUser(user);
                            // 设置登录用户信息
                            if (updateSuccess) {
                                // 如果成功，保存User变量，
                                coreManager.setSelf(user);
                                updateTitle(mViewPager.getCurrentItem());
                            }
                        }

                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }
}
